package com.example.speeddating.exception;

import com.example.speeddating.common.BaseResponse;
import com.example.speeddating.common.RespGenerator;
import com.example.speeddating.enums.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.server.ServerErrorException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value=CommonException.class)
    @ResponseBody
    public BaseResponse<Object> handleCommonException(CommonException e){
        return RespGenerator.returnError(e.getCode(),e.getMessage());
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    Object handleException(Exception e){
//        log.error("请求错误，请求地址{}错误信息:",request.getRequestURI(),e);
        BaseResponse responseVo = new BaseResponse<>();
        if (e instanceof NoHandlerFoundException){
//            404
            responseVo.setCode(ResponseCodeEnum.CODE_404.getCode());
            responseVo.setMessage(ResponseCodeEnum.CODE_404.getMsg());
        }else if (e instanceof CommonException){
//            业务错误
            CommonException biz = (CommonException) e;
            responseVo.setCode(biz.getCode());
            responseVo.setMessage(biz.getMessage());
        }else if(e instanceof BindException || e instanceof MethodArgumentTypeMismatchException){
//            参数类型错误
            responseVo.setCode(ResponseCodeEnum.CODE_600.getCode());
            responseVo.setMessage(ResponseCodeEnum.CODE_600.getMsg());
        }else if(e instanceof DuplicateKeyException){
//            主键冲突
            responseVo.setCode(ResponseCodeEnum.CODE_601.getCode());
            responseVo.setMessage(ResponseCodeEnum.CODE_601.getMsg());
        }else {
            responseVo.setCode(ResponseCodeEnum.CODE_500.getCode());
            responseVo.setMessage(ResponseCodeEnum.CODE_500.getMsg());
        }
        return RespGenerator.returnError(responseVo.getCode(),responseVo.getMessage());
    }


}
